package com.kaifamiao.wendao.servlet;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.TopicService;
import com.kaifamiao.wendao.util.Pagination;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet( "/topic/list/mine" )
public class TopicListMineServlet extends HttpServlet {

    @Override
    protected void doGet( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        // 获得会话对象
        HttpSession session = request.getSession();

        // 尝试从会话中获取 customer
        Customer c = (Customer)session.getAttribute( "customer" );
        if( c == null ) {
            session.setAttribute( "message" , "请先登录" );
            response.sendRedirect( request.getContextPath() + "/customer/sign/in");
            return ;
        }

        final Integer size = 3 ; // 每页最多显示的行数

        // 尝试从请求参数中获取 current
        String current = request.getParameter( "current" );
        // 如果 current 不存在或者是空串，则指定一个默认值
        if( current == null || ( current = current.trim() ).isEmpty() ) {
            current = "1" ;
        }

        Integer currentPage = Integer.valueOf( current ); // 当前页码

        TopicService ts = new TopicService();
        Integer cid = c.getId() ;
        Integer total = ts.countMinePages( cid , size ); // 统计总页数
        // 查询当前已登录用户所发布的所有话题
        List<Topic> list = ts.loadMine( cid , currentPage , size );
        // 使用有参构造创建 Pagination 对象
        Pagination<Topic> pagination = new Pagination<>( size , total , currentPage , list );
        // 将 Pagination 设置到 request 的属性中
        request.setAttribute( "pagination" , pagination );

        String path = "/WEB-INF/pages/topic/mine.jsp" ;
        RequestDispatcher dispatcher = request.getRequestDispatcher( path );
        dispatcher.forward( request , response );

    }

}
